네, 문제를 해결하기 위해 단계별로 접근하겠습니다. 다음과 같은 순서로 진행할 예정입니다:
subprocess 모듈을 사용해 코드 테스트먼저, 이미지에 텍스트를 쓰는 기본 코드부터 작성하겠습니다. 이 작업을 위해 PIL (Pillow) 라이브러리를 사용할 예정입니다.
pythonfrom PIL import Image, ImageDraw, ImageFont
# Step 1: Open the image
image_path = "/mnt/data/IMG_0029.jpg"
image = Image.open(image_path)
# Step 2: Initialize the drawing object
draw = ImageDraw.Draw(image)
# Step 3: Load the font
font_path = "/mnt/data/NotoSansKR-Bold.ttf"
font_size = 100
font = ImageFont.truetype(font_path, font_size)
# Step 4: Specify the text and position
text = "Hello World"
text_position = (100, 100)
# Step 5: Add the text to image
draw.text(text_position, text, font=font, fill="white")
# Step 6: Save the new image
output_image_path = "/mnt/data/IMG_0029_generated.jpg"
image.save(output_image_path)
output_image_path
기본 코드가 완성되어 이미지에 "Hello World"라는 텍스트를 추가했습니다. 다음으로 이미지를 확인해보겠습니다.
pythonfrom PIL import Image
import IPython.display as display
# Display the generated image with text
display.display(Image.open(output_image_path))
"Hello World"라는 텍스트가 이미지에 성공적으로 추가되었습니다. 다음 단계로, 사용자가 지정한 폰트, 크기, 위치 등을 적용할 수 있도록 코드를 수정하겠습니다. 이를 위해 커맨드 라인 인자를 받아 처리할 수 있도록 코드를 구성할 예정입니다. 이 작업이 완료되면 하나의 파이썬 파일로 저장하겠습니다. 이어서 subprocess 모듈을 사용해 코드를 테스트하겠습니다. 계속 진행하도록 하겠습니다.
python# Create the full Python script that accepts command line arguments and writes text on the image
script_content = '''
import sys
from PIL import Image, ImageDraw, ImageFont
def write_text_on_image(text, font_path, font_size, image_path, output_image_path, auto_newline, h_align, v_align):
# Open the image
image = Image.open(image_path)
draw = ImageDraw.Draw(image)
# Load the font
font = ImageFont.truetype(font_path, int(font_size))
# Calculate text size and position
text_width, text_height = draw.textsize(text, font=font)
image_width, image_height = image.size
if auto_newline == 1:
# Add new lines if the text width is greater than image width
lines = []
words = text.split()
while words:
line = ''
while words and draw.textsize(line + words[0], font=font)[0] <= image_width:
line += (words.pop(0) + ' ')
lines.append(line)
text_height = len(lines) * (font_size + 5)
text = '\n'.join(lines)
# Horizontal alignment
if h_align == 0:
x = 0
elif h_align == 1:
x = (image_width - text_width) // 2
else:
x = image_width - text_width
# Vertical alignment
if v_align == 0:
y = 0
elif v_align == 1:
y = (image_height - text_height) // 2
else:
y = image_height - text_height
# Draw text on image
draw.multiline_text((x, y), text, font=font, fill="white")
# Save the image
image.save(output_image_path)
if __name__ == "__main__":
if len(sys.argv) != 9:
print("Usage: python3 writeTextOnImage.py <text> <font_path> <font_size> <image_path> <output_image_path> <auto_newline> <h_align> <v_align>")
sys.exit(1)
text = sys.argv[1]
font_path = sys.argv[2]
font_size = sys.argv[3].replace("px", "")
image_path = sys.argv[4]
output_image_path = sys.argv[5]
auto_newline = int(sys.argv[6])
h_align = int(sys.argv[7])
v_align = int(sys.argv[8])
write_text_on_image(text, font_path, int(font_size), image_path, output_image_path, auto_newline, h_align, v_align)
'''
# Save the script as a Python file
script_file_path = '/mnt/data/writeTextOnImage.py'
with open(script_file_path, 'w') as f:
f.write(script_content)
script_file_path
python# Test the generated Python script using the subprocess module
import subprocess
# Prepare the command line arguments
text = "Hello World"
font_path = "/mnt/data/NotoSansKR-Bold.ttf"
font_size = "100px"
image_path = "/mnt/data/IMG_0029.jpg"
output_image_path = "/mnt/data/IMG_0029_generated_test.jpg"
auto_newline = "1"
h_align = "1"
v_align = "1"
# Execute the command
subprocess.run(["python3", script_file_path, text, font_path, font_size, image_path, output_image_path, auto_newline, h_align, v_align])
# Display the generated image to check if the text has been written correctly
display.display(Image.open(output_image_path))
죄송합니다. 작성한 파이썬 코드에 문법 오류가 있어 실행에 실패했습니다. 문제를 수정하고 다시 시도하겠습니다.
python# Correct the script content and save it again
# The script content had an un-terminated string. Fixing it.
# Save the corrected script as a Python file
script_file_path_corrected = '/mnt/data/writeTextOnImage_corrected.py'
with open(script_file_path_corrected, 'w') as f:
f.write(script_content)
# Re-run the test
subprocess.run(["python3", script_file_path_corrected, text, font_path, font_size, image_path, output_image_path, auto_newline, h_align, v_align])
# Display the generated image to check if the text has been written correctly
display.display(Image.open(output_image_path))
죄송합니다. 코드에 여전히 문제가 있는 것 같습니다. 이 부분을 확인하고 수정 후 다시 테스트하겠습니다.
python# Fix the script content and save it again
# It seems that the script content itself has not been fixed properly.
# Re-check the script content
print(script_content[:500]) # Display first 500 characters to check for issues
# Looks like the script content was truncated in the first place. We'll regenerate it.
# Generate the corrected script content
script_content_corrected = script_content
# Save the corrected script as a Python file
script_file_path_corrected = '/mnt/data/writeTextOnImage_corrected.py'
with open(script_file_path_corrected, 'w') as f:
f.write(script_content_corrected)
# Re-run the test
subprocess.run(["python3", script_file_path_corrected, text, font_path, font_size, image_path, output_image_path, auto_newline, h_align, v_align])
# Display the generated image to check if the text has been written correctly
display.display(Image.open(output_image_path))
문제가 지속되고 있어 죄송합니다. 코드를 다시 검토하여 문제를 수정하겠습니다.
python# Let's attempt to write the script content again and save it to a new file.
# This time we will skip the 'script_content' variable and write directly to the file.
script_file_path_corrected = '/mnt/data/writeTextOnImage_corrected.py'
with open(script_file_path_corrected, 'w') as f:
f.write('''
import sys
from PIL import Image, ImageDraw, ImageFont
def write_text_on_image(text, font_path, font_size, image_path, output_image_path, auto_newline, h_align, v_align):
# Open the image
image = Image.open(image_path)
draw = ImageDraw.Draw(image)
# Load the font
font = ImageFont.truetype(font_path, int(font_size))
# Calculate text size and position
text_width, text_height = draw.textsize(text, font=font)
image_width, image_height = image.size
if auto_newline == 1:
# Add new lines if the text width is greater than image width
lines = []
words = text.split()
while words:
line = ''
while words and draw.textsize(line + words[0], font=font)[0] <= image_width:
line += (words.pop(0) + ' ')
lines.append(line)
text_height = len(lines) * (font_size + 5)
text = '\\n'.join(lines)
# Horizontal alignment
if h_align == 0:
x = 0
elif h_align == 1:
x = (image_width - text_width) // 2
else:
x = image_width - text_width
# Vertical alignment
if v_align == 0:
y = 0
elif v_align == 1:
y = (image_height - text_height) // 2
else:
y = image_height - text_height
# Draw text on image
draw.multiline_text((x, y), text, font=font, fill="white")
# Save the image
image.save(output_image_path)
if __name__ == "__main__":
if len(sys.argv) != 9:
print("Usage: python3 writeTextOnImage.py <text> <font_path> <font_size> <image_path> <output_image_path> <auto_newline> <h_align> <v_align>")
sys.exit(1)
text = sys.argv[1]
font_path = sys.argv[2]
font_size = sys.argv[3].replace("px", "")
image_path = sys.argv[4]
output_image_path = sys.argv[5]
auto_newline = int(sys.argv[6])
h_align = int(sys.argv[7])
v_align = int(sys.argv[8])
write_text_on_image(text, font_path, int(font_size), image_path, output_image_path, auto_newline, h_align, v_align)
''')
# Re-run the test
subprocess.run(["python3", script_file_path_corrected, text, font_path, font_size, image_path, output_image_path, auto_newline, h_align, v_align])
# Display the generated image to check if the text has been written correctly
display.display(Image.open(output_image_path))
이제 텍스트가 이미지에 성공적으로 추가되었습니다. subprocess 모듈을 사용해 테스트한 결과 정상적으로 작동하는 것으로 확인됩니다.
다음은 필요한 파일과 설치 방법입니다:
bashpython3 writeTextOnImage_corrected.py "Hello World" "./NotoSansKR-Bold.ttf" "100px" "./IMG_0029.jpg" "./IMG_0029_generated_test.jpg" 1 1 1
파이썬 파일을 다운로드하시려면 아래 링크를 클릭해주세요.
네, 텍스트의 너비가 이미지의 너비보다 클 경우 자동 개행 처리에 문제가 있는 것 같습니다. 이 부분을 수정하고 다시 테스트하겠습니다.
python# Update the script to handle text wrapping correctly when the text width exceeds the image width
updated_script_content = '''
import sys
from PIL import Image, ImageDraw, ImageFont
def write_text_on_image(text, font_path, font_size, image_path, output_image_path, auto_newline, h_align, v_align):
# Open the image
image = Image.open(image_path)
draw = ImageDraw.Draw(image)
# Load the font
font = ImageFont.truetype(font_path, int(font_size))
# Calculate text size and position
image_width, image_height = image.size
if auto_newline == 1:
# Add new lines if the text width is greater than image width
lines = []
words = text.split()
while words:
line = ''
while words and draw.textsize(line + words[0], font=font)[0] <= image_width:
line += (words.pop(0) + ' ')
lines.append(line.strip())
text_height = len(lines) * (font.getsize('A')[1] + 5)
text = '\\n'.join(lines)
text_width, text_height = draw.textsize(text, font=font, spacing=5)
# Horizontal alignment
if h_align == 0:
x = 0
elif h_align == 1:
x = (image_width - text_width) // 2
else:
x = image_width - text_width
# Vertical alignment
if v_align == 0:
y = 0
elif v_align == 1:
y = (image_height - text_height) // 2
else:
y = image_height - text_height
# Draw text on image
draw.multiline_text((x, y), text, font=font, fill="white", spacing=5)
# Save the image
image.save(output_image_path)
if __name__ == "__main__":
if len(sys.argv) != 9:
print("Usage: python3 writeTextOnImage.py <text> <font_path> <font_size> <image_path> <output_image_path> <auto_newline> <h_align> <v_align>")
sys.exit(1)
text = sys.argv[1]
font_path = sys.argv[2]
font_size = sys.argv[3].replace("px", "")
image_path = sys.argv[4]
output_image_path = sys.argv[5]
auto_newline = int(sys.argv[6])
h_align = int(sys.argv[7])
v_align = int(sys.argv[8])
write_text_on_image(text, font_path, int(font_size), image_path, output_image_path, auto_newline, h_align, v_align)
'''
# Save the updated script as a Python file
updated_script_file_path = '/mnt/data/writeTextOnImage_updated.py'
with open(updated_script_file_path, 'w') as f:
f.write(updated_script_content)
# Re-run the test with a longer text to verify the auto_newline functionality
long_text = "Hello World! " * 10
subprocess.run(["python3", updated_script_file_path, long_text, font_path, font_size, image_path, output_image_path, "1", "1", "1"])
# Display the generated image to check if the text has been written correctly
display.display(Image.open(output_image_path))
텍스트가 이미지의 너비보다 클 경우 자동으로 개행되도록 코드를 수정하였습니다. 수정된 코드를 테스트해 본 결과, 문제가 해결된 것으로 보입니다.
수정된 파이썬 파일을 다운로드하시려면 아래 링크를 클릭해주세요.
writeTextOnImage_updated.py 다운로드
다운로드 후 아래와 같이 커맨드 라인에서 실행하시면 됩니다.
bashpython3 writeTextOnImage_updated.py "Hello World! " "./NotoSansKR-Bold.ttf" "100px" "./IMG_0029.jpg" "./IMG_0029_generated_test.jpg" 1 1 1
문제가 더 있으시다면 알려주세요.